package com.library.servlet.admin;

import com.library.entity.Book;
import com.library.entity.Bookcopy;
import com.library.entity.po.BookCopyPO;
import com.library.entity.po.PagePO;
import com.library.service.admin.BookCopyService;
import com.library.servlet.BaseServlet;
import com.library.dao.BookManageDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/bookcopy")
public class BookCopyServlet extends BaseServlet {

    private final BookCopyService bookCopyService = new BookCopyService();
    private final BookManageDao bookManageDao = new BookManageDao();

    /**
     * 分页查询书籍副本管理页面
     */
    protected void bookCopyManage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        String keyword = request.getParameter("keyword");

        int pageNum = 1;
        int pageSize = 5;

        // 解析分页参数
        if (pageNumStr != null && !pageNumStr.isEmpty()) {
            try {
                pageNum = Integer.parseInt(pageNumStr);
                if (pageNum < 1) pageNum = 1;
            } catch (NumberFormatException e) {
                pageNum = 1;
            }
        }

        if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
            try {
                pageSize = Integer.parseInt(pageSizeStr);
                if (pageSize < 1) pageSize = 5;
            } catch (NumberFormatException e) {
                pageSize = 5;
            }
        }

        try {
            // 获取分页数据
            PagePO<BookCopyPO> bookCopyPOPagePO = bookCopyService.pageBookCopy(pageNum, pageSize, keyword, request);
            request.setAttribute("bookCopyPOPagePO", bookCopyPOPagePO);

            // 保持搜索关键词
            if (keyword != null && !keyword.trim().isEmpty()) {
                request.setAttribute("keyword", keyword);
            }

            // 获取所有已上架的书籍列表，用于添加副本的下拉框
            List<Book> availableBooks = bookManageDao.getAvailableBooks();
            request.setAttribute("availableBooks", availableBooks);

            request.getRequestDispatcher("/WEB-INF/admin/bookCopyManage.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("BookCopyServlet 异常: " + e.getMessage());
            request.setAttribute("error", "system");
            request.getRequestDispatcher("/WEB-INF/admin/bookCopyManage.jsp").forward(request, response);
        }
    }

    /**
     * 添加书籍副本
     */
    protected void addBookCopy(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String isbn = request.getParameter("ISBN");
        String barCode = request.getParameter("barCode");
        String place = request.getParameter("place");

        try {
            // 参数验证
            if (isbn == null || isbn.trim().isEmpty() ||
                    barCode == null || barCode.trim().isEmpty() ||
                    place == null || place.trim().isEmpty()) {

                request.setAttribute("error", "param");
                bookCopyManage(request, response);
                return;
            }

            // 验证条码格式
            if (!bookCopyService.isValidBarCode(barCode)) {
                request.setAttribute("error", "invalidbarcode");
                bookCopyManage(request, response);
                return;
            }

            // 验证书籍是否存在且上架
            if (!bookCopyService.isBookAvailableForCopy(isbn)) {
                request.setAttribute("error", "booknotfound");
                bookCopyManage(request, response);
                return;
            }

            // 新添加的副本默认状态为1（可借）
            Integer status = 1;

            Bookcopy bookcopy = new Bookcopy(isbn, place, status, barCode);
            boolean success = bookCopyService.addBookcopy(bookcopy);

            if (success) {
                request.setAttribute("success", "add");
            } else {
                request.setAttribute("error", "addfailed");
            }

            bookCopyManage(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "system");
            bookCopyManage(request, response);
        }
    }

    /**
     * 更新书籍副本
     */
    protected void updateBookCopy(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String barCode = request.getParameter("barCode");
        String place = request.getParameter("place");
        String statusStr = request.getParameter("status");

        try {
            if (barCode == null || barCode.trim().isEmpty() ||
                    place == null || place.trim().isEmpty() ||
                    statusStr == null || statusStr.trim().isEmpty()) {

                request.setAttribute("error", "param");
                bookCopyManage(request, response);
                return;
            }

            Integer status = Integer.parseInt(statusStr);

            if (status < 0 || status > 2) {
                request.setAttribute("error", "invalidstatus");
                bookCopyManage(request, response);
                return;
            }

            // 检查副本当前状态
            Bookcopy existingCopy = bookCopyService.getBookCopyByBarCode(barCode);
            if (existingCopy == null) {
                request.setAttribute("error", "notfound");
                bookCopyManage(request, response);
                return;
            }

            // 如果副本当前是借出状态，不允许修改状态（只能修改位置）
            if (existingCopy.getStatus() == 0 && status != 0) {
                request.setAttribute("error", "borrowedcannotchange");
                bookCopyManage(request, response);
                return;
            }

            boolean success = bookCopyService.updateBookCopy(barCode, place, status);

            if (success) {
                request.setAttribute("success", "update");
            } else {
                request.setAttribute("error", "updatefailed");
            }

            bookCopyManage(request, response);

        } catch (NumberFormatException e) {
            request.setAttribute("error", "numberformat");
            bookCopyManage(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "system");
            bookCopyManage(request, response);
        }
    }

    /**
     * 删除单个书籍副本（注销）
     */
    protected void deleteBookCopy(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String barCode = request.getParameter("barCode");

        if (barCode == null || barCode.trim().isEmpty()) {
            request.setAttribute("error", "param");
            bookCopyManage(request, response);
            return;
        }

        try {
            boolean success = bookCopyService.cancelBookCopy(barCode);

            if (success) {
                request.setAttribute("success", "delete");
            } else {
                request.setAttribute("error", "deletefailed");
            }

            bookCopyManage(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "system");
            bookCopyManage(request, response);
        }
    }

    /**
     * 批量删除书籍副本（注销）
     */
    protected void batchDeleteBookCopy(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String[] barCodes = request.getParameterValues("barCodes");

        if (barCodes == null || barCodes.length == 0) {
            request.setAttribute("error", "nobatch");
            bookCopyManage(request, response);
            return;
        }

        try {
            boolean success = bookCopyService.batchCancelBookCopy(barCodes);

            if (success) {
                request.setAttribute("success", "batchdelete");
            } else {
                request.setAttribute("error", "batchdeletefailed");
            }

            bookCopyManage(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "system");
            bookCopyManage(request, response);
        }
    }

    /**
     * 搜索书籍副本（实际调用bookCopyManage方法）
     */
    protected void searchBookCopy(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        bookCopyManage(request, response);
    }

    /**
     * 获取副本详细信息（用于编辑弹窗）
     */
    protected void getBookCopyInfo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String barCode = request.getParameter("barCode");

        response.setContentType("application/json;charset=UTF-8");

        if (barCode == null || barCode.trim().isEmpty()) {
            response.getWriter().write("{\"success\":false,\"message\":\"条码号不能为空\"}");
            return;
        }

        try {
            Bookcopy bookcopy = bookCopyService.getBookCopyByBarCode(barCode);
            if (bookcopy != null) {
                String json = String.format(
                        "{\"success\":true,\"data\":{\"barCode\":\"%s\",\"isbn\":\"%s\",\"place\":\"%s\",\"status\":%d}}",
                        bookcopy.getBarCode(),
                        bookcopy.getISBN(),
                        bookcopy.getPlace() != null ? bookcopy.getPlace() : "",
                        bookcopy.getStatus()
                );
                response.getWriter().write(json);
            } else {
                response.getWriter().write("{\"success\":false,\"message\":\"副本不存在\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"success\":false,\"message\":\"系统错误\"}");
        }
    }
}